<template>
  <div class="select-label">
    <el-form ref="formDataRef" :model="dataForm" :rules="formRules" label-position="right" class="lineHeight32" label-width="80px">
      <div v-for="(item,index) in tags" :key="item.uuid">
        <div v-if="!isHide" class="filter-item">
          <el-form-item
            :prop="'labelname'+index"
            label="标签名称"
            style="margin-right: 16px;margin-bottom: 0;">
            <el-input
              v-model.trim="item.tagName"
              maxlength="20"
              size="small"
              placeholder="请填写标签名称"
              name="name"
              type="text"
              @change="tabNameChange"/>
          </el-form-item>
          <div v-if="tags.length > 1" class="delete-btn" @click="deleteItem(index)">
            <i class="delete-icon el-icon-delete"/>
          </div>
          <!-- 向上 -->
          <el-tooltip content="往前移" placement="top">
            <i v-if="index !== 0" class="index-icon el-icon-top" @click="changeIndex('top',index)"/>
            <i v-else class="index-icon el-icon-top" style="color:#999;cursor:not-allowed;" />
          </el-tooltip>
          <!-- 向下 -->
          <el-tooltip content="往后移" placement="top">
            <i v-if="index !== tags.length-1" class="index-icon el-icon-bottom" @click="changeIndex('bottom',index)"/>
            <i v-else class="index-icon el-icon-bottom" style="color:#999;cursor:not-allowed;" />
          </el-tooltip>
          <!-- 复制 -->
          <el-tooltip content="复制" placement="top">
            <i class="index-icon el-icon-copy-document" @click="copyTag(item)" />
          </el-tooltip>
          <!-- 隐藏标签 -->
          <el-tooltip v-if="!item.tagType" :content="`隐藏标签:${item.hideTag === 1?'隐藏':'显示'}`" placement="top">
            <i :style="item.hideTag === 0?{color: '#406eff'}:{color: '#999'}" class="eye-icon el-icon-view" @click="changeHideTag(item)"/>
          </el-tooltip>

          <!-- <el-checkbox v-if="!item.tagType" v-model="item.hideTag" :false-label="0" :true-label="1" style="margin-left:20px;">隐藏标签</el-checkbox> -->
        </div>
        <div v-if="!item.tagType" class="label-props">
          <el-form-item
            :prop="`fieldName${index}`"
            label="选取字段"
            label-width="6em"
            style="margin-bottom: 24px;"
            class="is-required select-field">
            <div class="flex-container">
              <el-select
                v-model="item.fieldCategorys"
                name="field"
                size="small"
                style="margin-right: 10px"
                popper-class="global-select-down"
                @change="selectFieldCategorys($event, item)">
                <!--<el-option :value="''" label="请选择" />-->
                <template v-for="item in fieldList">
                  <el-option
                    v-if="item.name !== '统计报表'"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </template>
                <el-option
                  :key="-1"
                  :label="'统计报表'"
                  :value="-1" />
              </el-select>
              <!-- 选择报表 -->
              <template v-if="isReportField(item.fieldCategorys)">
                <selectWithUserLoad
                  v-model="item.reportId"
                  :loadmore-method="getRemoteReport()"
                  placeholder="请选择报表"
                  key-name="id"
                  label-name="name"
                  extend-class="select-report"
                  class="width120"
                  filterable
                  style="margin-right:10px;"
                  collapse-tags
                  clearable
                  @change="getReportFieldFun($event, item, true)"
                />
              </template>
              <el-select v-model="item.fieldId" size="small" popper-class="global-select-down" name="field">
                <!--<el-option :value="''" label="请选择" />-->
                <el-option
                  v-for="item in item.fieldChidrenList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
              <span class="tip-word">的</span>
              <el-select v-model="item.filedFormula" size="small" popper-class="global-select-down" class="widthdiy120" name="field">
                <!--<el-option :value="''" label="请选择" />-->
                <el-option
                  v-for="item in filedFormulaOpt"
                  :key="item"
                  :label="item"
                  :value="item" />
              </el-select>
              <div v-if="showExtend" style="margin-left: 10px;">
                <el-checkbox v-model="item.editTarget" :true-label="1" :false-label="0">编辑目标值</el-checkbox>
              </div>
            </div>
            <div v-if="item.editTarget" class="flex-container" style="margin-top: 10px;">
              <div class="target-title">目标数据：</div>
              <el-input
                v-model="item.targetData"
                oninput="if(value>1000000000)value=1000000000"
                type="number"
                class="width190"
                placeholder="默认与该字段相除"
                size="small"
                @mousewheel.native.prevent
              />
            </div>
          </el-form-item>
          <el-form-item label="数据筛选" label-width="6em" prop="dataFilter">
            <DataFilter
              :ref="'DataFilterRef'+item.uuid "
              :is-filter-report="true"
              :is-contrast="isContrast && !item.editTarget"
              params-type="id"/>
          </el-form-item>
        </div>
        <div v-else class="label-props">
          <OverviewFormula v-model="item.formulaOrigin" :tags-options="handelData(tags)" />
          <el-form-item label="单位" label-width="80px" style="margin-bottom: 0px;margin-top:15px;">
            <el-input v-model="item.unit" size="small" placeholder="不超过10个字符" maxlength="10" />
          </el-form-item>
        </div>
      </div>
      <el-form-item v-if="!isHide" label-width="0px" style="margin-bottom: 14px">
        <PlainCreateBtn size="small" @click="addItem(0)">添加常规标签</PlainCreateBtn>
        <PlainCreateBtn size="small" @click="addItem(1)">添加公式标签</PlainCreateBtn>
        <!-- <el-button type="primary" size="small" @click="addItem(0)">添加常规标签</el-button>
        <el-button type="primary" size="small" @click="addItem(1)">添加公式标签</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getFieldList, getOptions, getReportList, getReportField } from '@/api/reportManage';
import addIcon from '@/assets/reportManage/add_icon.png';
// component
import DataFilter from '@/components/ReportManage/dataFilter/index';
import OverviewFormula from './module/overviewFormula';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
// tool
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { generateUUID } from '@/utils/tools';
export default {
  name: 'SelectLabel',
  components: { DataFilter, OverviewFormula, selectWithUserLoad },
  props: {
    isHide: { // 数字翻页器不展示标题
      type: Boolean,
      default: false
    },
    isContrast: { // 数字翻页器不展示对比
      type: Boolean,
      default: false
    },
    showExtend: {
      type: Boolean,
      default: false
    },
    removeDuplicate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      addIcon,
      dataForm: {},
      systemWord: ['系统字段'], // 系统字段
      // filedFormulaOpt: ['求和', '平均数', '计数'],
      tags: [{
        uuid: generateUUID(),
        unit: '',
        tagType: 0,
        hideTag: 0,
        tagName: '',
        reportId: '',
        fieldId: '',
        filedFormula: '',
        fieldCategorys: '',
        dataFiltering: [],
        dataItemFiltering: []
      }],
      // formRules: {
      //   labelname: [{ required: true, trigger: 'blur', validator: validateInput() }]
      // },
      conditionOptions: [],
      mathOperationOptions: []
    };
  },
  computed: {
    ...mapState({
      'fieldList': state => state.options.fieldList,
      'collectOptions': state => state.options.collectOptions
    }),
    formRules() {
      const tags = this.tags;
      const formRules = {};
      const validateInput = (msg) => {
        return (rule, value, callback) => {
          const res = tags[rule.index].tagName;
          if (!res || res === '') { callback(new Error(msg)); } else { callback(); }
        };
      };
      tags.forEach((i, index) => {
        formRules[`labelname${index}`] = [{ required: true, trigger: 'blur', validator: validateInput('请填写标签名称'), index: index }];
      });
      return formRules;
    },
    filedFormulaOpt() {
      if (this.removeDuplicate) {
        return ['求和', '平均数', '计数', '计数(去重)'];
      } else {
        return ['求和', '平均数', '计数'];
      }
    }
  },
  created() {
    this.getOpt();
    this.getField();
  },
  methods: {
    getLabelData() {
      const tags = JSON.parse(JSON.stringify(this.tags));

      tags.forEach((i, index) => {
        const uuid = i.uuid || index;
        if (this.$refs[`DataFilterRef${uuid}`] && this.$refs[`DataFilterRef${uuid}`].length) {
          const filterListGroup = JSON.parse(JSON.stringify(this.$refs[`DataFilterRef${uuid}`][0].getParamsData()));
          i.dataFiltering = filterListGroup.report || [];
          i.dataItemFiltering = filterListGroup.system || [];
        } else {
          i.dataFiltering = [];
          i.dataItemFiltering = [];
        }
        // 公式标签
        if (i.tagType === 1) {
          let tagFormula = '';
          const formulaVariable = [];
          if (i.formulaOrigin && i.formulaOrigin.length > 0) {
            i.formulaOrigin.forEach(j => {
              if (j.type === 'var') {
                delete j.dataFiltering;
                delete j.dataItemFiltering;
                delete j.fieldChidrenList;
                const varObj = {
                  editTarget: j.editTarget,
                  targetData: j.targetData ? Number(j.targetData) : j.targetData,
                  name: j.tagName
                };
                formulaVariable.push(varObj);
                tagFormula = tagFormula + '#' + j.tagName + '#';
              } else {
                tagFormula = tagFormula + j.tagName;
              }
              const notDelete = ['targetData', 'editTarget', 'type', 'tagName', 'label'];
              for (const key in j) {
                if (!notDelete.includes(key)) {
                  delete j[key];
                }
              }
            });
          }
          i.formulaVariable = formulaVariable;
          i.tagFormula = tagFormula;
          i.formulaOrigin = i.formulaOrigin ? JSON.stringify(i.formulaOrigin) : '';
        } else {
          i.formulaOrigin = '';
        }
      });
      return tags;
    },
    setDefault(tagsData, createUUID = true) {
      this.callback = function() {
        const tags = _.cloneDeep(tagsData);
        tags.forEach((k, index) => {
          (createUUID || !k.uuid) && (k.uuid = generateUUID());
          // 这步操作是为了让常规标签和公式中的标签建立连接，时修改常规标签时，公式中的标签能自动修改
          if (k.tagType === 1) {
            if (k.formulaOrigin && k.formulaOrigin !== '') {
              k.formulaOrigin = JSON.parse(k.formulaOrigin);
            }
            if (k.formulaOrigin && k.formulaOrigin.length) {
              for (let j = 0; j < k.formulaOrigin.length; j++) {
                tags.forEach(i => {
                  if (!i.tagType && k.formulaOrigin[j].type === 'var' && i.tagName === k.formulaOrigin[j].tagName) {
                    i.type = 'var';
                    k.formulaOrigin[j] = i;
                  }
                });
              }
            }
          }
          // 统计报表单独处理
          // const report = this.fieldList.find(i => i.name === '统计报表');
          if (k.reportId) {
            k.fieldCategorys = -1;
            k.fieldCategorysName = '统计报表';
            this.getReportFieldFun(k.reportId, k);
          } else {
            this.fieldList.forEach(i => {
              i.fieldInfo.forEach(j => {
                if (Number(j.id) === Number(k.fieldId)) {
                  k.fieldCategorys = i.id;
                  k.fieldChidrenList = i.fieldInfo;
                  k.fieldCategorysName = i.name;
                }
              });
            });
          }
          this.$nextTick(() => {
            if (this.$refs[`DataFilterRef${k.uuid}`] && this.$refs[`DataFilterRef${k.uuid}`].length) {
              this.$refs[`DataFilterRef${k.uuid}`][0].setDefault([{ report: k.dataFiltering, system: k.dataItemFiltering }]);
            }
          });
        });
        this.tags = tags;
      };
      if (this.fieldList && this.fieldList.length) {
        this.callback();
      }
    },
    async getField(name = '') {
      try {
        const res = await getFieldList({ name, use: 2 });
        if (res.data) {
          this.$store.commit('SET_FIELDLIST', res.data);
          if (this.callback) {
            this.callback();
          }
        }
      } catch (error) {
        console.error(error);
      }
    },
    // tagType 0:普通标签 1:公式标签
    addItem(tagType = 0) {
      const item = {
        tagType: tagType,
        unit: '',
        tagName: '',
        fieldId: '',
        reportId: '',
        filedFormula: '',
        hideTag: 0,
        dataFiltering: {
          type: 1,
          field: '',
          operation: '',
          fieldCategorysName: '',
          value: ''
        },
        fieldCategorys: ''
      };
      if (tagType === 1) {
        item.tagFormula = '';
        item.formulaVariable = [];
        item.formulaOrigin = []; // 原数据
        item.unit = '';
      }
      item.uuid = generateUUID();
      this.tags.push(item);
    },
    deleteItem(index) {
      const deleteItemData = this.tags[index];
      // 删除tag是，删除其他公式标签的引用
      if (!deleteItemData.tagType) {
        this.tags.forEach(i => {
          if (i.tagType === 1 && i.formulaOrigin) {
            this.deleteFindIndexVar(i.formulaOrigin, deleteItemData);
          }
        });
      }
      this.tags.splice(index, 1);
      this.$emit('tagDelete');
    },
    deleteFindIndexVar(formulaOrigin, deleteItemData) {
      const varIndex = formulaOrigin.findIndex((j) => {
        return j.uuid === deleteItemData.uuid;
      });
      if (varIndex !== -1) {
        formulaOrigin.splice(varIndex, 1);
        this.deleteFindIndexVar(formulaOrigin, deleteItemData);
      }
    },
    selectFieldCategorys(id, item) {
      item.reportId = '';
      if (id === '') {
        item.fieldChidrenList = [];
        item.fieldCategorysName = '';
        item.fieldId = '';
        item.fieldCategorys = '';
        return;
      }
      this.fieldList.forEach(i => {
        if (i.id === id) {
          item.fieldChidrenList = i.fieldInfo;
          item.fieldCategorysName = i.name;
        }
      });
      item.fieldCategorys = id;
      item.fieldId = '';
      if (this.isReportField(id)) {
        item.fieldChidrenList = [];
      }
    },
    changeSelectCondition(name, item) {
      const conditionOptions = this.conditionOptions;
      conditionOptions.forEach(i => {
        if (i.name === name) {
          item.conditionChilderOptions = i.options;
        }
      });
      item.value = '';
    },
    // 上移下移
    changeIndex(type, index) {
      const arr = this.tags.splice(index, 1);
      if (type === 'bottom') {
        this.tags.splice(index + 1, 0, arr[0]);
      } else if (type === 'top') {
        this.tags.splice(index - 1, 0, arr[0]);
      }
    },
    // 隐藏标签
    changeHideTag(item) {
      item.hideTag = item.hideTag === 1 ? 0 : 1;
    },
    // 复制标签
    copyTag(item) {
      const formulaOrigin = item.formulaOrigin || [];
      const tagItem = _.cloneDeep(item);
      if (this.$refs[`DataFilterRef${tagItem.uuid}`] && this.$refs[`DataFilterRef${tagItem.uuid}`].length) {
        const filterListGroup = JSON.parse(JSON.stringify(this.$refs[`DataFilterRef${tagItem.uuid}`][0].getParamsData()));
        tagItem.dataFiltering = filterListGroup.report || [];
        tagItem.dataItemFiltering = filterListGroup.system || [];
      } else {
        tagItem.dataFiltering = [];
        tagItem.dataItemFiltering = [];
      }
      tagItem.formulaOrigin = [...formulaOrigin];
      tagItem.uuid = generateUUID();
      let index = 0;
      const tagName = `${tagItem.tagName}-副本`;
      this.tags.forEach(i => {
        if (i.tagName.indexOf(tagName) >= 0) {
          index++;
        }
      });
      if (index > 0) {
        tagItem.tagName = tagName + index;
      } else {
        tagItem.tagName = tagName;
      }
      this.tags.push(tagItem);
      ElMessage.success('复制成功');
      this.$nextTick(() => {
        if (this.$refs[`DataFilterRef${tagItem.uuid}`] && this.$refs[`DataFilterRef${tagItem.uuid}`].length) {
          this.$refs[`DataFilterRef${tagItem.uuid}`][0].setDefault([{ report: tagItem.dataFiltering, system: tagItem.dataItemFiltering }]);
        }
      });
    },
    handelData(tags) {
      const res = tags.filter(i => {
        return !i.tagType && i.tagName !== '';
      });
      return res;
    },
    // 获取报表筛选相关下拉选项
    async getOpt() {
      const collectOptions = this.collectOptions;
      if (collectOptions && collectOptions.conditionOptions) {
        this.conditionOptions = collectOptions.conditionOptions.condition;
        this.mathOperationOptions = collectOptions.conditionOptions.mathOptions;
      } else {
        try {
          const res = await getOptions();
          if (res.data) {
            this.conditionOptions = res.data.conditionOptions.condition;
            this.mathOperationOptions = res.data.conditionOptions.mathOptions;
          }
        } catch (error) {
          console.error(error);
        }
      }
    },
    // 选择统计报表逻辑
    isReportField(id) {
      const item = this.fieldList.find(i => i.id === id);
      return id === -1 || (item && item.name === '统计报表');
    },
    getRemoteReport() {
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.reportName = '';
          params.isCreateChart = true;
          params.notShowNoAuthTip = 1;
          if (params.userName) params.reportName = params.userName;
          getReportList(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },
    getReportFieldFun(id, item, isChange) {
      if (!item.reportId) {
        this.$set(item, 'fieldChidrenList', []);
        this.$set(item, 'fieldId', '');
        this.$forceUpdate();
        return;
      }
      if (isChange) item.fieldId = '';
      const params = {
        reportId: item.reportId
      };
      getReportField(params).then((res) => {
        if (res.data) {
          this.$set(item, 'fieldChidrenList', res.data);
          this.$forceUpdate();
        }
      });
    },
    tabNameChange(val) {
      this.$emit('tabNameChange', val);
    }
  }
};
</script>
<style lang="scss" scoped>
.select-label {
  ::v-deep .el-input__inner::placeholder {
    color: #999 !important;
  }
  ::v-deep .el-input__icon {
    color: #333 !important;
  }
  .filter-item {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    .add-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 30px;
      height: 30px;
      cursor: pointer;
      border-radius:4px;
      background-color: #EFF3FB;
      img {
        width: 16px;
        height: 16px;
      }
    }
    .delete-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 30px;
      height: 30px;
      cursor: pointer;
      .delete-icon {
        font-size: 16px;
        color: #6C6C6C;
      }
    }
  }
  .label-props {
    // margin-left: 70px;
    margin-bottom: 24px;
    min-width:616px;
    display: inline-block;
    border-radius:4px;
    background-color: #FAFAFA;
    // border:1px solid #DCDFE6;
    position: relative;
    padding: 20px 20px 20px 6px;
    @media screen and (max-width: 1340px) {
      padding: 20px 10px;
    }
    &::before {
      content: '';
      width: 0;
      height: 0;
      border: 10px solid #FAFAFA;
      border-top-color: transparent;
      border-right-color: transparent;
      // border-bottom-color: transparent;
      border-left-color: transparent;
      position: absolute;
      top: -18px;
      left: 20px;
    }
    & ::v-deep {
      .select-field {
        .el-input__inner {
          width: 120px !important;
        }
      }
      .el-form-item {
        &:last-child {
          margin-bottom: 0 !important;
        }
      }
      .width190 {
        .el-input__inner {
          width: 190px !important;
        }
      }
      .width160 {
        .el-input__inner {
          width: 160px !important;
        }
      }
    }
    .tip-word {
      font-size:14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(153,153,153,1);
      line-height:14px;
      margin: 0 12px;
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }
}
.flex-container {
  display: flex;
  align-items: center;
  .el-select {
    ::v-deep .el-input__inner{
      padding-right: 20px !important;
    }
    ::v-deep .el-input__suffix{
      right: 0 !important;
    }
  }
}
.target-title {
  width: 90px;
  color: #999;
}
.width200 {
  & ::v-deep {
    .el-input__inner {
      width: 200px !important;
    }
  }
}
.index-icon {
  font-size: 16px;
  cursor: pointer;
  color: #406eff;
  margin-right: 10px;
}
.eye-icon {
  font-size: 16px;
  cursor: pointer;
  color: #406eff;
  margin-right: 10px;
}
</style>
